import numpy as np
from sklearn.cluster import DBSCAN
from sklearn import metrics
from sklearn.datasets.samples_generator import make_blobs  #为聚类产生数据集
from sklearn.preprocessing import StandardScaler           #归一化
from matplotlib import pyplot as plt

plt.rcParams['font.sans-serif']=['SimHei']      #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False        #用来正常显示负号

centers = [[1, 1], [-1, -1], [1, -1]]           #样本中心,这里可以加中心点，下面的样本数也可以加
X, labels_true = make_blobs(n_samples=750, centers=centers, cluster_std=0.4, random_state=0)
'''样本点数750；样本中心为3个点；数据集的标准差0.4'''
X = StandardScaler().fit_transform(X)
'''对数据进行归一化,然后fit_transform(X)，意思是找出X的\mu和\sigma，并应用在X上。'''

db = DBSCAN(eps=0.3, min_samples=10).fit(X)     #DBSCAN方法实施，ϵ-邻域0.3；ϵ-邻域（半径）内样本数为10
core_samples_mask = np.zeros_like(db.labels_, dtype=bool)    #这几行的指标需要结合metrics再学习一下！
core_samples_mask[db.core_sample_indices_] = True
labels = db.labels_
n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)

print('Estimated number of clusters: %d' % n_clusters_)
print("Homogeneity: %0.3f" % metrics.homogeneity_score(labels_true, labels))
print("Completeness: %0.3f" % metrics.completeness_score(labels_true, labels))
print("V-measure: %0.3f" % metrics.v_measure_score(labels_true, labels))
print("Adjusted Rand Index: %0.3f"
      % metrics.adjusted_rand_score(labels_true, labels))
print("Adjusted Mutual Information: %0.3f"
      % metrics.adjusted_mutual_info_score(labels_true, labels))
print("Silhouette Coefficient: %0.3f"
      % metrics.silhouette_score(X, labels))

'''评估指标
Estimated number of clusters: 3     估计簇数
Homogeneity: 0.953                  同质性：每个群集只包含单个类的成员
Completeness: 0.883                 完整性：给定类的所有成员都分配给同一个群集
V-measure: 0.917                    上面两者的调和平均
Adjusted Rand Index: 0.952          在计算样本预测值和真实值之间的相似度，同属于这一类或都不属于这一类，而不考虑数据元素顺序和归一化
Adjusted Mutual Information: 0.916  利用基于互信息的方法来衡量聚类效果需要实际类别信息
Silhouette Coefficient: 0.626       轮廓系数'''

unique_labels = set(labels)         #噪声处理，奇异点
colors = [plt.cm.Spectral(each)
          for each in np.linspace(0, 1, len(unique_labels))]
for k, col in zip(unique_labels, colors):
    if k == -1:
        col = [0, 0, 0, 1]

    class_member_mask = (labels == k)

    xy = X[class_member_mask & core_samples_mask]
    plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col),
             markeredgecolor='k', markersize=14)

    xy = X[class_member_mask & ~core_samples_mask]
    plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col),
             markeredgecolor='k', markersize=6)

plt.title('估计类的数量: %d' % n_clusters_)
plt.show()
#图中的黑点为噪声点